// 配置路由相关信息
import Vue from 'vue'
import Router from 'vue-router'

// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'
// import Message from '../components/Message'
// import News from '../components/News'
// import Profile from '../components/Profile'

// 路由懒加载
const Home = () => import('../components/Home');
const About = () => import('../components/About');
const User = () => import('../components/User');
const Message = () => import('../components/Message');
const News = () => import('../components/News');
const Profile = () => import('../components/Profile');

// 1.注入插件
Vue.use(Router);

// 2.定义路由
const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: {
      title: '首页'
    },
    children: [
      // {
      //   path: '/',
      //   redirect: 'message'
      // },
      {
        path: 'message',
        component: Message
      },
      {
        path: 'news',
        component: News
      }
    ]
  },
  {
    path: '/about',
    component: About,
    meta: {
      title: '关于'
    }
  },
  {
    path: '/user/:userId',
    component: User,
    meta: {
      title: '用户'
    }
  },
  {
    path: '/profile',
    component: Profile,
    meta: {
      title: '档案'
    }
  }
];

// 3.创建router实例
const router = new Router({
  routes: routes,
  // 默认情况下，路径的改变使用的URL的hash，如果希望使用HTML5的history模式，需要进行如下配置
  mode: 'history',
  // 当<router-link>对应的路由匹配成功时，会自动给当前元素设置一个router-link-active的class，设置linkActiveClass: 'active'可以修改class的默认名称
  linkActiveClass: 'active'
});

// vue-router提供的导航守卫主要用来监听路由的进入和离开
// vue-router提供了beforeEach和afterEach两个钩子函数，它们会在路由即将改变前和改变后触发，在beforeEach中必须主动调用next()函数，afterEach不需要主动调用next()函数
// to: 即将进入的目标路由对象 from: 当前导航即将离开的路由对象 next: 调用该方法后才能进入下一个钩子

// 前置守卫(guard)
router.beforeEach((to, from, next) => {
  // console.log(to);
  console.log("进入 beforeEach 方法...");
  window.document.title = to.matched[0].meta.title;
  next();
});

// 后置钩子(hook)
router.afterEach((to, from) => {
  // console.log(to);
  console.log("进入 afterEach 方法...");
});

// 4.导出router实例
export default router;
